package com.mobisys.live.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import static com.mobisys.live.config.Config.APP_BIZID;
import static com.mobisys.live.config.Config.PUSH_URL_KEY;
import static com.mobisys.live.config.Config.RTMP_VALID_TIME;

/**
 * Created by zhuo on 2018-01-24.
 */
public class LiveUtil {


    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }

    /**
     * 获取流的有效时间
     * @param nowTime
     * @return
     */
    public static long createTxTime(long nowTime)
    {
        //	$now_time = time();
        nowTime += RTMP_VALID_TIME;//3 hours
        return nowTime;//conver hex
    }

    /**
     * KEY+ stream_id + txTime
     * @param key
     * @param streamId
     * @param txTime
     * @return
     */
    public static String getSafeUrl(String key, String streamId, long txTime) {
        String input = new StringBuilder().
                append(key).
                append(streamId).
                append(Long.toHexString(txTime).toUpperCase()).toString();

        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }

    /**
     * 获取streamId
     * @param liveId 使用liveId 来拼接
     * @return
     */
    public static String generateLiveCode(String liveId){
        String liveCode=APP_BIZID+"_"+liveId;
        return liveCode;
    }

    /**
     * 获取streamId
     * 因为同一个租户可能有多个频道（每个频道里面有一个直播），所以同一个租户可能有多个直播，因而需要加上频道
     * 号来加以区分
     * @param userId
     * @param channelNum
     * @return
     */
    public static String generateLiveCode(String userId,String channelNum){
        String liveCode=generateLiveCode(userId)+"_"+channelNum;
        return liveCode;
    }

    /**
     * 获取推流地址
     * @param userId
     * @return
     */
    public static String getStreamUrl(String userId){
        String safeChain=getSafeUrl(PUSH_URL_KEY,generateLiveCode(userId),createTxTime(System.currentTimeMillis()/1000));
        String streamUrl="rtmp://"+APP_BIZID+".livepush.myqcloud.com/live/"+generateLiveCode(userId)+"?bizid="+APP_BIZID+"&"+safeChain;
        return streamUrl;
    }

    /**
     * 获取推流地址
     * @param userId
     * @param channelNum
     * @return
     */
    public static String getStreamUrl(String userId,String channelNum){
        String steamId=generateLiveCode(userId,channelNum);
        String safeChain=getSafeUrl(PUSH_URL_KEY,steamId,createTxTime(System.currentTimeMillis()/1000));
        String streamUrl="rtmp://"+APP_BIZID+".livepush.myqcloud.com/live/"+steamId+"?bizid="+APP_BIZID+"&"+safeChain;
        return streamUrl;
    }

    /**
     * 获取RTMP播放地址
     * @param userId
     * @return
     */
    public static String getRTMPPlayUrl(String userId){
        String RTMPPlayUrl="rtmp://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId);
        return RTMPPlayUrl;
    }

    /**
     *
     * @param userId
     * @param channelNum
     * @return
     */
    public static String getRTMPPlayUrl(String userId,String channelNum){
        String RTMPPlayUrl="rtmp://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId,channelNum);
        return RTMPPlayUrl;
    }

    /**
     * 获取HLS播放地址
     * @param userId
     * @return
     */
    public static String getHLSPlayUrl(String userId){
        String HLSPlayUrl="http://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId)+".m3u8";
        return HLSPlayUrl;
    }

    /**
     *
     * @param userId
     * @param channelNum
     * @return
     */
    public static String getHLSPlayUrl(String userId,String channelNum){
        String HLSPlayUrl="http://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId,channelNum)+".m3u8";
        return HLSPlayUrl;
    }

    /**
     * 获取FLV播放地址
     * @param userId
     * @return
     */
    public static String getFLVPlayUrl(String userId){
        String FLVPlayUrl="http://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId)+".flv";
        return FLVPlayUrl;
    }

    /**
     *
     * @param userId
     * @param channelNum
     * @return
     */
    public static String getFLVPlayUrl(String userId,String channelNum){
        String FLVPlayUrl="http://"+APP_BIZID+".liveplay.myqcloud.com/live/"+generateLiveCode(userId,channelNum)+".flv";
        return FLVPlayUrl;
    }


    /**
     * 生成频道号，为8位整数（按照100万个用户，每个用户10个频道来估算）
     * @return
     */
    public static long generateChannelNum(){
        //拿时间戳作为种子
        return System.currentTimeMillis()%1000;
    }


    public static void main(String[] args) {
        System.out.println(getSafeUrl("txrtmp", "11212122", 1469762325L));
    }


}
